<?php
/**
 * Created by PhpStorm.
 * Author: Fedax
 * Date: 2017/6/30
 * Time: 17:41
 */

namespace app\admin\controller;
use tree\Tree;
use app\admin\model\AuthAccess as AuthAccessModel;
use app\admin\model\Menu as MenuModel;
/**
 * 角色权限
 * Class Role
 * @package app\admin\controller
 */
class AuthAccess extends Index
{

    /**
     * 设置角色权限
     * @return \think\response\View
     */
    public function index()
    {
        $menuModel = new MenuModel();
        $authModel = new AuthAccessModel();
        //角色ID
        $tree       = new Tree();
        $tree->icon = ['│ ', '├─ ', '└─ '];
        $tree->nbsp = '&nbsp;&nbsp;&nbsp;';

        $result = $menuModel->menuCache();
        $newMenus      = [];
        $privilegeData = $authModel->getRuleVals(input('id'));//获取权限表数据
        foreach ($result as $m) {
            $newMenus[$m['id']] = $m;
        }

        foreach ($result as $n => $t) {
            $result[$n]['checked']      = ($this->_isChecked($t, $privilegeData)) ? ' checked' : '';
            $result[$n]['level']        = $this->_getLevel($t['id'], $newMenus);
            $result[$n]['style']        = empty($t['parent_id']) ? '' : 'display:none;';
            $result[$n]['parentIdNode'] = ($t['parent_id']) ? ' class="child-of-node-' . $t['parent_id'] . '"' : '';
        }
        $str = "<tr id='node-\$id'\$parentIdNode  style='\$style'>
                   <td style='padding-left:30px;'>\$spacer<input type='checkbox' name='menuId[]' value='\$id' level='\$level' \$checked onclick='javascript:checknode(this);'> \$name</td>
    			</tr>";
        $tree->init($result);

        $category = $tree->getTree(0, $str);

        $this->assign("category", $category);
        $this->assign("roleId", input('id'));
        return view();
    }

    /**
     * 检查指定菜单是否有权限
     * @param array $menu menu表中数组
     * @param $privData
     * @return bool
     */
    private function _isChecked($menu, $privData)
    {
        $app    = $menu['app'];
        $model  = $menu['controller'];
        $action = $menu['action'];
        $param = $menu['param'];
        $name   = strtolower("$app/$model/$action");
        if ($param) {
            $name = strtolower("$app/$model/$action" . '?' . $param);
        }
        if ($privData) {
            if (in_array($name, $privData)) {
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }

    }
    /**
     * 获取菜单深度
     * @param $id
     * @param array $array
     * @param int $i
     * @return int
     */
    protected function _getLevel($id, $array = [], $i = 0)
    {
        if ($array[$id]['parent_id'] == 0 || empty($array[$array[$id]['parent_id']]) || $array[$id]['parent_id'] == $id) {
            return $i;
        } else {
            $i++;
            return $this->_getLevel($array[$id]['parent_id'], $array, $i);
        }
    }



    /**
     * 角色授权提交
     * @return \think\response\Redirect
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function saveData()
    {
        if (request()->isPost()) {

            $roleId = $this->request->param("roleId", 0, 'intval');
            if (!$roleId) {
                $this->error('需要授权的角色不存在');
            }
            $authAccessModel = new AuthAccessModel();
            if (is_array($this->request->param('menuId/a')) && count($this->request->param('menuId/a')) > 0) {
                $menuModel = new MenuModel();
                $authAccessModel->where("role_id", $roleId)->delete();
                foreach ($_POST['menuId'] as $menuId) {
                    $menu = $menuModel->where(["id" => $menuId])->field("app,controller,action,param")->find();
                    if ($menu) {
                        $app    = $menu['app'];
                        $model  = $menu['controller'];
                        $action = $menu['action'];
                        $param =  $menu['param'];
                        $name   = strtolower("$app/$model/$action");
                        if ($param) {
                            $name = strtolower("$app/$model/$action" . '?' . $param);
                        }
                        $authAccessModel->insert(["role_id" => $roleId, "rule_name" => $name]);
                    }
                }
                $this->success(lang('operate') . lang('success'));
            } else {
                //当没有数据时，清除当前角色授权
                $authAccessModel->where(["role_id" => $roleId])->delete();
                $this->error('没有接收到数据，执行清除授权成功！');
            }
        }
        return redirect('/Miss');
    }
}